<!--
  -    Copyright (c) 2018-2025, lengleng All rights reserved.
  -
  - Redistribution and use in source and binary forms, with or without
  - modification, are permitted provided that the following conditions are met:
  -
  - Redistributions of source code must retain the above copyright notice,
  - this list of conditions and the following disclaimer.
  - Redistributions in binary form must reproduce the above copyright
  - notice, this list of conditions and the following disclaimer in the
  - documentation and/or other materials provided with the distribution.
  - Neither the name of the pig4cloud.com developer nor the names of its
  - contributors may be used to endorse or promote products derived from
  - this software without specific prior written permission.
  - Author: lengleng (wangiegie@gmail.com)
  -->
<template>
	<div class="layout-padding">
		<div class="layout-padding-auto layout-padding-view">
			<div class="execution">
					<avue-crud
						ref="crud"
						v-model:defaults="defaults"
						v-model="form"
						:page="page"
						:data="tableData"
						:table-loading="tableLoading"
						:option="tableOption"
						:before-open="handleOpenBefore"
						:before-close="handleCloseBefore"
						:permission="permissionList"
						@selection-change="selectionChange"
						@on-load="getList"
						@search-change="searchChange"
						@search-reset="searchReset"
						@refresh-change="refreshChange"
						@size-change="sizeChange"
						@current-change="currentChange"
						@row-update="handleUpdate"
						@row-save="handleSave"
						@row-del="rowDel"
					>
						
						<template #subareaArea-form>
							<div class="unit-title">
								<div class="unit-input">
									<el-input-number style="width: 400px" v-model="form.subareaArea" type="number" :precision="2" placeholder="请输入分区面积">
									</el-input-number>
								</div>
								<div class="unit-btn">
									<div>
										<el-button style="display: inline-block" type="primary" plain @click="getDevForm">面积参考值</el-button>
									</div>
									<div style="width: 465px; margin-left: 10px">{{ referenceValue }}</div>
								</div>
							</div>
						</template>
						<template #menu-left="{}">
							<el-button class="filter-item" v-if="permissions.access_accessSubarea_add" type="primary" icon="el-icon-edit" @click="$refs.crud.rowAdd()">添加 </el-button>
							<el-button class="filter-item" v-if="permissions.access_accessSubarea_import" plain type="primary" icon="el-icon-upload" @click="$refs.excelUpload.show()">导入 </el-button>
							<!-- <el-button class="filter-item" v-if="permissions.access_accessSubarea_export" plain type="primary" icon="el-icon-download" @click="exportExcel">导出 </el-button> -->
							<el-button class="filter-item" v-if="permissions.access_accessSubarea_del" type="primary" icon="el-icon-edit" @click="pldetele">批量删除 </el-button>
						</template>
						<template #menu-right="{}">
						<el-button class="filter-item"  v-auth="'access_accessSubarea_export'" circle icon="Download"  @click="exportExcel"></el-button>
					</template>
						<template #menu="{ row, index, size }">
							<el-button
								v-if="!row.isson && permissions.access_accessSubarea_add"
								text
								type="primary"
								icon="el-icon-plus"
								:size="size"
								@click="addarea(row, index)"
								>添加子分区
							</el-button>

							<el-button v-if="!row.isson" text type="primary" icon="el-icon-plus" :size="size" @click="nbarea(row)"
								>内部分区({{ row.childrens ? row.childrens.length : 0 }})
							</el-button>
						</template>

						<template #subareaJzbm-form>
							<avue-select
								v-model="form.subareaJzbm"
								placeholder="请选择建筑"
								:dic="buildingsOptions"
								:props="buildingsProps"
								@change="placenoChange"
								:disabled="isupdate"
							></avue-select>
						</template>
						<template #subareaLc-form>
							<avue-select
								v-model="form.subareaLc"
								placeholder="请选择楼层"
								:dic="floorsOptions"
								:props="floorsProps"
								@change="placenoChangeFloor"
								:disabled="isupdate"
							></avue-select>
						</template>
						<template #subareadCode-form>
							<avue-select
								v-model="form.subareadCode"
								placeholder="请选择分区"
								:filterable="true"
								:dic="subareaOptions"
								:props="subareaProps"
								@change="changeSubarea"
								:disabled="isupdate"
							></avue-select>
						</template>
						<template #subareaJzbm-search>
							<avue-select
								v-model="searchForm.subareaJzbm"
								placeholder="请选择建筑"
								:dic="buildingssearchOptions"
								:props="buildingsProps"
								@change="placenoChangesearch"
								@keyup.enter="getList"
							></avue-select>
						</template>
						<template #subareaLc-search>
							<avue-select
								v-model="searchForm.subareaLc"
								placeholder="请选择楼层"
								:dic="floorssearchOptions"
								:props="floorsProps"
								@keyup.enter="getList"
							></avue-select>
						</template>
						<template #subareaCn-search>
							<avue-input v-model="searchForm.subareaCn" placeholder="请输入 分区名称" @keyup.enter="getList"></avue-input>
						</template>
					</avue-crud>
					<el-dialog v-model="visible" :destroy-on-close="true" title="内部分区" width="90%" @close="close">
						<avue-crud
							ref="crud"
							v-model:defaults="defaults"
							v-model="form2"
							v-model:page="page2"
							:data="tableData2"
							:table-loading="tableLoading"
							:option="tableOption2"
							:before-open="handleOpenBefore2"
							:permission="permissionList"
							@selection-change="selectionChange"
							@on-load="getSonList"
							@search-change="searchChange2"
							@search-reset="searchReset2"
							@refresh-change="refreshChange"
							@size-change="sizeChange"
							@current-change="currentChange"
							@row-update="handleUpdate"
							@row-save="handleSave"
							@row-del="rowDel"
						>
							<template #subareaJzbm-form>
								<avue-select
									v-model="form2.subareaJzbm"
									placeholder="请选择建筑"
									:dic="buildingsOptions"
									:props="buildingsProps"
									@change="placenoChange"
									disabled
								></avue-select>
							</template>
							<template #subareaLc-form>
								<avue-select v-model="form2.subareaLc" placeholder="请选择楼层" :dic="floorsOptions" :props="floorsProps" disabled></avue-select>
							</template>
							<template #subareaCn-search>
								<avue-input v-model="searchForm.subareaCn" placeholder="请输入 分区名称" @keyup.enter="getSonList"></avue-input>
							</template>
							<template #subareadCode-form>
								<avue-select
									v-model="form2.subareadCode"
									placeholder="请选择分区"
									:filterable="true"
									:dic="subareaOptions"
									:props="subareaProps"
									disabled
								></avue-select>
							</template>
							<template #menu-left="{}">
								<el-button v-if="permissions.access_accessSubarea_import" class="filter-item" plain type="primary" icon="el-icon-upload" @click="openInport">导入 </el-button>
								<el-button v-if="permissions.access_accessSubarea_del" class="filter-item" type="primary" icon="el-icon-edit" @click="pldetele">批量删除 </el-button>
							</template>
						</avue-crud>
						<excel-upload
							ref="excelUpload1"
							title="空间分区信息导入"
							url="/bm/bamssubarea/batch/import"
							temp-name="空间分区信息.xlsx"
							temp-url="/bm/sys-file/local/subareabacth.xlsx"
							:datacs="inputData"
							@refreshDataList="handleRefreshChange"
						></excel-upload>
					</el-dialog>
					<!--excel 模板导入 -->
					<excel-upload
						ref="excelUpload"
						title="空间分区信息导入"
						url="/bm/bamssubarea/import"
						temp-name="空间分区信息.xlsx"
						temp-url="/bm/sys-file/local/file/subarea.xlsx"
						@refreshDataList="handleRefreshChange"
					></excel-upload>
			</div>
		</div>
	</div>
</template>

<script>
import { fetchList, getObj, addObj, putObj, delObj, getTree, getBamSubareaCode, getAllList, delObjs } from '/@/api/basiciot/area/fenqu';
import { getAllBuildings, getFenquCountArea } from '/@/api/basiciot/area/buildings';
import { getAllFloor } from '/@/api/basiciot/area/floor';
import { tableOption, tableOption2 } from '/@/crud/basiciot/area/fenqu';




import ExcelUpload from '/@/components/ExcelUpload/index.vue';

import { getAuthBtnList} from '/@/utils/btnpermissions'
import other from '/@/utils/other';


export default {
	name: 'bamsubarea',
	components: { ExcelUpload },
	data() {
		return {
			defaults: {},
			searchForm: {},
			tableData: [],
			tableData2: [],
			page: {
				total: 0, // 总页数
				currentPage: 1, // 当前页数
				pageSize: 10, // 每页显示多少条
			},
			page2: {
				total: 0, // 总页数
				currentPage: 1, // 当前页数
				pageSize: 10, // 每页显示多少条
			},
			tableLoading: false,
			tableOption: tableOption,
			tableOption2: tableOption2,
			buildingsOptions: [],
			buildingsProps: {
				label: 'buildingsCn',
				value: 'buildingsId',
			},
			floorsOptions: [],
			floorsProps: {
				label: 'floorCn',
				value: 'floorCode',
			},
			bdic: null,
			fdic: null,
			form: {},
			form2: {},
			last_unitno: '',
			front_unitno: '',

			buildingssearchOptions: [],
			floorssearchOptions: [],
			subareaLc: '',
			subareaJzbm: '',
			ischangecode: true,
			ischangecode1: true,
			subareaOptions: [],
			subareaProps: {
				label: 'subareaCn',
				value: 'subareaCode',
			},
			isaddCode: false,
			visible: false,
			objdata: {},
			sonclose: false,
			isupdate: false,
			selectdatas: [],
			inputData: {
				subareadCode: '',
			},
			showcode: false,
			referenceValue: ''
		};
	},
	computed: {
		permissionList() {
			return {
				addBtn: getAuthBtnList('access_accessSubarea_add'),
				delBtn: getAuthBtnList('access_accessSubarea_del'),
				editBtn: getAuthBtnList('access_accessSubarea_edit'),
			};
		},
		permissions() {
			return {
				access_accessSubarea_view : getAuthBtnList('access_accessSubarea_view'),
				access_accessSubarea_add: getAuthBtnList('access_accessSubarea_add'),
				access_accessSubarea_edit: getAuthBtnList('access_accessSubarea_edit'),
				access_accessSubarea_del: getAuthBtnList('access_accessSubarea_del'),
				access_accessSubarea_export: getAuthBtnList('access_accessSubarea_export'),
				access_accessSubarea_import: getAuthBtnList('access_accessSubarea_import')
			}
		}
	},
	mounted() {
		getAllFloor({}).then((res) => {
			this.floorssearchOptions = res.data;
		});
		getAllBuildings({}).then((res) => {
			this.buildingssearchOptions = res.data;
		});
	},
	methods: {
		openInport() {
			this.$refs.excelUpload1.show();
			this.inputData.subareadCode = this.objdata.subareaCode;
		},
		pldetele() {
			if (this.selectdatas.length > 0) {
				this.$confirm('是否确认删除已选的数据', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning',
				})
					.then(() => {
						let nes = [];
						this.selectdatas.forEach((data) => {
							nes.push(data.subareaId);
						});
						return delObjs(nes);
					})
					.then(() => {
						this.$message.success('删除成功');
						this.getList(this.page);
						this.getSonList(this.page2);
					});
			}
		},
		selectionChange(data) {
			this.selectdatas = data;
		},
		close() {
			this.page2.currentPage = 1;
			this.sonclose = false;
		},
		nbarea(data) {
			this.visible = true;
			//console.log(data);
			this.objdata = data;
			this.sonclose = true;
		},
		addarea(row, index) {
			this.showcode = true;
			this.form.subareaJzbm = row.subareaJzbm;
			this.form.subareaLc = row.subareaLc;
			this.form.subareadCode = row.subareaCode;

			this.isaddCode = true;
			this.ischangecode = false;
			this.isupdate = true;
			this.$refs.crud.rowAdd();

			// getBamSubareaCode({
			//     code:row.subareaCode,
			//     level:'3',
			//     suffix:''
			// }).then(res=>{
			//      this.form.subareaCode=res.data.data
			// })
		},
		changeSubarea(data) {
			if (data.value) {
				if (this.ischangecode1) {
					getBamSubareaCode({
						code: data.value,
						level: '3',
						suffix: '',
					}).then((res) => {
						if (this.sonclose) {
							this.form2.subareaCode = res.data;
						} else {
							this.form.subareaCode = res.data;
						}
					});
				}
				this.ischangecode1 = true;
			}
		},
		handleOpenBefore2(show, type) {
			getAllBuildings({}).then((res) => {
				this.buildingsOptions = res.data;
			});
			getAllFloor({}).then((res) => {
				this.floorsOptions = res.data;
			});
			getAllList({}).then((res) => {
				this.subareaOptions = res.data;
			});
			this.form2.subareaJzbm = this.objdata.subareaJzbm;
			this.form2.subareaLc = this.objdata.subareaLc;
			this.form2.subareadCode = this.objdata.subareaCode;

			if (type === 'edit') {
				// if(!this.form2.isson){
				//     this.defaults.subareadCode.display =false
				// }
				// else{
				//     this.defaults.subareadCode.display =true
				// }
				this.last_unitno = this.form2.subareaCode && this.form2.subareaCode.substr(this.form2.subareaLc.length, 4);
				this.ischangecode = false;
				this.ischangecode1 = false;
			} else if (type === 'add') {
				getBamSubareaCode({
					code: this.objdata.subareaCode,
					level: 3,
					suffix: '',
				}).then((res) => {
					this.form2.subareaCode = res.data;
				});
				this.isaddCode = false;
				//this.defaults2.subareadCode.display =true
				this.last_unitno = '';
			}
			show();
		},
		handleCloseBefore(done, type) {
			this.isupdate = false;
			this.showcode = false;
			this.defaults.subareadCode.display = false;
			done();
		},
		handleOpenBefore(show, type) {
			this.referenceValue = '';
			getAllBuildings({}).then((res) => {
				this.buildingsOptions = res.data;
			});
			getAllFloor({}).then((res) => {
				this.floorsOptions = res.data;
			});
			getAllList({}).then((res) => {
				this.subareaOptions = res.data;
			});
			this.defaults.subareaJzbm.disabled = false;
			this.defaults.subareaLc.disabled = false;
			this.defaults.subareadCode.disabled = false;
			if (type === 'edit') {
				// if(!this.form.isson){
				//     this.defaults.subareadCode.display =false
				// }
				// else{
				//     this.defaults.subareadCode.display =true
				// }
				this.last_unitno = this.form.subareaCode && this.form.subareaCode.substr(this.form.subareaLc.length, 4);
				this.ischangecode = false;
				this.ischangecode1 = false;
				if (this.showcode) {
					this.defaults.subareadCode.display = true;
					this.defaults.subareadCode.disabled = false;

					this.form.remark = '';
					this.form.subareaCoords = '';
					this.form.sort = 0;
					this.form.subareaEn = '';
					this.form.subareaCn = '';
					this.form.subareaId = '';
				}
			} else if (type === 'add') {
				if (this.isaddCode) {
					//  this.defaults.subareaJzbm.disabled=true
					//  this.defaults.subareaLc.disabled=true
					//  this.defaults.subareadCode.disabled=true
				}
				if (this.showcode) {
					this.defaults.subareadCode.display = true;
					this.defaults.subareadCode.disabled = false;
					//this.form.subareadCode=this.form.subareaCode
					getBamSubareaCode({
						code: this.form.subareadCode,
						level: 3,
						suffix: '',
					}).then((res) => {
						this.form.subareaCode = res.data;
					});
					this.form.remark = '';
					this.form.subareaCoords = '';
					this.form.sort = 0;
					this.form.subareaEn = '';
					this.form.subareaCn = '';
					this.form.subareaId = '';
				}
				this.isaddCode = false;
				//this.defaults.subareadCode.display =true
				this.last_unitno = '';
			}
			show();
		},
		getSonList(page, params) {
			this.tableLoading = true;
			fetchList(
				Object.assign(
					{
						current: page.currentPage,
						size: page.pageSize,
					},
					params,
					this.searchForm,
					{ subareadCode: this.objdata.subareaCode }
				)
			)
				.then((response) => {
					this.tableData2 = response.data.records;
					this.page2.total = response.data.total;
					this.tableLoading = false;
				})
				.catch(() => {
					this.tableLoading = false;
				});
		},
		getList(page, params) {
			this.tableLoading = true;
			fetchList(
				Object.assign(
					{
						current: page.currentPage,
						size: page.pageSize,
					},
					params,
					this.searchForm
				)
			)
				.then((response) => {
					this.tableData = response.data.records;
					// this.tableData.forEach(s=>{
					//     s.children=s.childrens
					//     s.children.forEach(t=>{
					//         t.isson=true
					//     })
					// })
					this.page.total = response.data.total;
					this.tableLoading = false;
				})
				.catch(() => {
					this.tableLoading = false;
				});
		},
		placenoChangesearch(data) {
			getAllFloor({ floorPid: data.value }).then((res) => {
				this.floorssearchOptions = res.data;
			});
		},
		rowDel: function (row, index) {
			let ts = '是否确认删除名称为' + row.subareaCn;
			if (row.childrens && row.childrens.length > 0) {
				ts = '有子分区是否确认删除';
			}
			this.$confirm(ts, '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			})
				.then(function () {
					return delObj(row.subareaId);
				})
				.then((data) => {
					this.$message.success('删除成功');
					this.getList(this.page);
					this.getSonList(this.page2);
				})
				.catch((cancelorerror) => {});
		},
		handleUpdate: function (row, index, done, loading) {
			//row.subareaCode=this.front_unitno+this.last_unitno
			putObj(row)
				.then((data) => {
					this.$message.success('修改成功');
					this.referenceValue = '';
					done();
					this.getList(this.page);
				})
				.catch(() => {
					loading();
				});
		},
		handleSave: function (row, done, loading) {
			//row.subareaCode=this.front_unitno+this.last_unitno
			if (row.subareadCode == '') {
				row.subareadCode = null;
			}
			addObj(row)
				.then((data) => {
					this.$message.success('添加成功');
					done();
					this.getList(this.page);
					this.getSonList(this.page2);
				})
				.catch(() => {
					loading();
				});
		},
		sizeChange(pageSize) {
			this.page.pageSize = pageSize;
			this.page2.pageSize = pageSize;
		},
		currentChange(current) {
			this.page.currentPage = current;
			this.page2.currentPage = current;
		},
		searchChange(form, done) {
			if (this.subareaJzbm) {
				form.subareaJzbm = this.subareaJzbm;
			}
			if (this.subareaLc) {
				form.subareaLc = this.subareaLc;
			}
			//this.searchForm = form
			this.page.currentPage = 1;
			this.getList(this.page, form);
			done();
		},
		searchChange2(form, done) {
			// if(this.subareaJzbm){
			//     form.subareaJzbm = this.subareaJzbm
			// }
			// if(this.subareaLc){
			//     form.subareaLc = this.subareaLc
			// }
			//this.searchForm = form
			this.page2.currentPage = 1;
			this.getSonList(this.page2, form);
			done();
		},
		searchReset() {
			this.subareaJzbm = '';
			this.subareaLc = '';
			this.searchForm = {};
			// delete this.searchForm.subareaJzbm
			// delete this.searchForm.subareaLc
			this.getList(this.page);
		},
		searchReset2() {
			this.searchForm = {};
		},
		refreshChange() {
			this.getList(this.page);
		},
		placenoChange(data) {
			getAllFloor({ floorPid: data.value }).then((res) => {
				this.floorsOptions = res.data;
			});
			this.front_unitno = '';
		},

		placenoChangeFloor(data) {
			if (data.value) {
				if (this.ischangecode) {
					getBamSubareaCode({
						code: data.value,
						level: 4,
						suffix: '',
					}).then((res) => {
						this.form.subareaCode = res.data;
					});
				}
				this.ischangecode = true;
			}
			//this.front_unitno =data.value
		},
		handleRefreshChange() {
			this.getList(this.page);
			this.getSonList(this.page2);
		},
		exportExcel() {
			other.downBlobFile(other.adaptationUrl('/admin/accessSubarea/export'), this.searchForm, '空间分区信息.xlsx');
		},
		treeLoad(tree, treeNode, resolve) {
			console.log(tree, treeNode);
			getAllList({ subareadCode: tree.subareaCode }).then((res) => {
				console.log(res.data.data);
				res.data.data.forEach((s) => (s.hasChildren = false));
				resolve(res.data.data);
			});
		},
		// 面积参考值
		getDevForm() {
			console.log(this.form.subareaId, 'formform');
			console.log('面级参考值');
			getFenquCountArea(this.form.subareaId).then((res) => {
				console.log(res.data.data, '面积参考值111');
				this.referenceValue = res.data.data;
			});
		},
	},
};
</script>
<style lang="scss" scoped>
.span-title {
	display: flex;
	background: rgb(226, 219, 219);
	border-radius: 4px;

	.span-label {
		padding-left: 10px;
		color: #fff;
		height: 36px;
		flex: 2;
	}

	.span-input {
		flex: 2;
	}
}

.unit-title {
	display: flex;

	.unit-input {
		flex: 2;
	}
}

.unit-btn {
	display: flex;
}
</style>
